package com.fingard.dsp.bank.directbank.spdb12;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.dsp.bank.directbank.spdb12.util.WtpFileUtil;
import com.fingard.io.FileHelper;
import com.fingard.net.*;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;

public class SPDB12ScheduleTask extends SPDB12Base implements IScheduleTask {
    public boolean isRunded = false;

    @Override
    public void execTask(TaskTimerSet timerSet) {
        try {
            if (timerSet.taskNameList.toLowerCase().contains("autoupload")) {
                autoupload();
            }
        } catch (Exception ex) {
            this.WriteBankLogLn(ex);
        }
    }

    public void autoupload() {
        try {
            // 获取日切时间判断是否可以执行定时任务
            Date tmpDateNow = new Date();
            String dayCutTime = getBankConfig().getValueAsString("dayCutTime");
            if (StringHelper.hasAnyChar(dayCutTime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(tmpDateNow);

                Calendar endCalendar = Calendar.getInstance();
                String time = String.format("%4s", dayCutTime.replace(":", "")).replace(" ", "0");
                endCalendar.setTime(Format.Time6Format.parse(time + "00"));
                endCalendar.add(Calendar.MINUTE, 1);
                String endDateTime = endCalendar.get(Calendar.HOUR_OF_DAY) + ":" + String.format("%2s",endCalendar.get(Calendar.MINUTE)).replace(" ", "0");

                int tmpDayCutTime = Integer.parseInt(dayCutTime.replace(":", ""));
                WriteBankLogLn("日切时间范围:[" + dayCutTime + "~" + endDateTime + "].");
                int tmpTimeNow = calendar.get(Calendar.HOUR_OF_DAY) * 100 + calendar.get(Calendar.MINUTE);
                String tmpTimeEnd = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);
                WriteBankLogLn("当前时间:[" + tmpTimeEnd + "].");
                if (tmpTimeNow >= tmpDayCutTime && (tmpTimeNow < Integer.parseInt(endDateTime.replace(":",""))) && !isRunded) {
                    // 开始执行文件上传任务
                    WriteBankLogLn("开始执行文件上传任务...");
                    String tmpPaySendDate = Format.Date8Format.format(calendar.getTime());

                    File tmpLocalMarkDir = new File(getDataFileDirectory(calendar.getTime()));
                    File[] upFileLists = tmpLocalMarkDir.listFiles();
                    for(File upFile : upFileLists) {
                        WriteBankLogLn2("批量授权请求文件路径: " + upFile.getAbsolutePath());

                        String detailFileMsg = FileHelper.readFileText(upFile.getAbsolutePath(), getCharset());
                        WriteBankLogLn("开始读取批次明细文件内容，用于读取明细总笔数拼接到汇总文件中,当日批次明细文件内容:\r\n" + detailFileMsg);

                        int totalNum = 0;
                        StringReader tmpStrReader = new StringReader(detailFileMsg);
                        BufferedReader tmpBuferReader = new BufferedReader(tmpStrReader);
                        while (true) {
                            String eachline = tmpBuferReader.readLine();
                            if (eachline == null) {
                                break;
                            }
                            totalNum++;
                        }
                        String totalContent = MessageFormat.format("F※{0}※1002※{1}※※※N\n", bankFront.corpNo, totalNum);
                        WriteBankLogLn("当前汇总文件内容:" + totalContent);

                        // 文件名命名规则: UBCS_保险公司编号(4位) _机构代码（4位）_日期（8位）_序号（2位）
                        FileHelper.writeFile(upFile.getAbsolutePath(), totalContent+detailFileMsg, getCharset());

                        //上送银保通服务器
                        FtpSet ftpSet = bankFront.getFtpSet("contract");

                        FtpReceiver ftpReceiver = null;
                        String requestType = getBankConfig().getValueAsString("requestType");
                        if (requestType != null && "SFTP".equals(requestType)) {
                            SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                            String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + upFile.getName();
                            ftpReceiver = sftpPortClient.uploadFile("", upFile.getAbsolutePath(), sftpFilePath);
                            sftpPortClient.disconnect();
                        } else {
                            FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                            ftpPortClient.setLocalPassiveMode();
                            ftpReceiver = ftpPortClient.uploadFile(upFile.getAbsolutePath(), upFile.getName());

                            ftpPortClient.disconnect();
                        }
                        if (!ftpReceiver.isCompleted) {
                            WriteBankLogLn("上传失败:"+ftpReceiver.connState+":"+ftpReceiver.connMsg);
                        } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                            WriteBankLogLn("上传失败:"+ftpReceiver.connState+":"+ftpReceiver.connMsg);
                        } else {
                            isRunded = true;
                            String[] tmpStrRet = WtpFileUtil.wtpUpload(bankFront.serverURL, upFile.getName(), ftpSet.upDir);
                            if (tmpStrRet[0].length() == 0) {
                                WriteBankLogLn("文件已上送银保通服务器并已发送通知给银保通");
                            } else {
                                WriteBankLogLn("文件通知失败，原因:" + tmpStrRet[1]);
                            }
                        }
                    }
                } else {
                    int tmpSpan = tmpDayCutTime - tmpTimeNow;
                    if (tmpSpan > 0) {
                        WriteBankLogLn("定时将于" + (tmpSpan / 60) + "小时后开始执行文件上传任务!");
                    } else {
                        WriteBankLogLn("定时将于" + (tmpSpan / 60 + 24) + "小时后开始执行文件上传任务!");
                    }
                }
            } else {
                WriteBankLogLn("配置文件缺失:'dayCutTime'配置节点，不进行文件上传,请及时更新配置文件!");
            }
        } catch (Exception ex) {
            WriteBankLogLn(ex);
        }
    }
}